<?php

import('@.Org.CommonTool');

/**
 * 自动返回表名字
 * @param	$tableName 
 * @example	order_info
 * @return	OrderInfo
 * 

function auto_table_name($table){
	$table_name_array	=	explode("_", $table);
	$tableName			=	'';
	if(count($table_name_array) > 1){
		foreach($table_name_array as $name){
			$tableName 	.=	ucwords($name);
		}
	}else{
		$tableName	=	ucwords( $table_name_array[0]);
	}
	return $tableName;
} 
*/

/**
 * 生成查询订单总金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_amount_field($alias = ''){
    return "   {$alias}goods_amount + {$alias}tax + {$alias}shipping_fee" .
           " + {$alias}insure_fee + {$alias}pay_fee + {$alias}pack_fee" .
           " + {$alias}card_fee ";
}



/**
 *  生成一个用户自定义时区日期的GMT时间戳
 *
 * @access  public
 * @param   int     $hour
 * @param   int     $minute
 * @param   int     $second
 * @param   int     $month
 * @param   int     $day
 * @param   int     $year
 *
 * @return void
 */
function local_mktime($hour = NULL , $minute= NULL, $second = NULL,  $month = NULL,  $day = NULL,  $year = NULL){
    $time = mktime($hour, $minute, $second, $month, $day, $year);
    return $time;
}

/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_query_sql($type = 'finished', $alias = ''){
    /* 已完成订单 */
    if ($type == 'finished'){
        return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
               " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship'){
        return " AND   {$alias}order_status " .
                 db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) .
               " AND   {$alias}shipping_status " .
                 db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) .
               " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay'){
        return " AND   {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
               " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed'){
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed'){
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship'){
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped'){
        return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " ";
    }
    else{
        die('函数 order_query_sql 参数错误');
    }
}

/**
 * 格式化重量：小于1千克用克表示，否则用千克表示
 * @param   float   $weight     重量
 * @return  string  格式化后的重量
 */
function formated_weight($weight){
    $weight = round(floatval($weight), 3);
    if ($weight > 0){
        if ($weight < 1){
            /* 小于1千克，用克表示 */
            return intval($weight * 1000) . L('gram');
        }
        else{
            /* 大于1千克，用千克表示 */
            return $weight . L('kilogram');
        }
    }
    else{
        return 0;
    }
}

/**
 * 取得支付方式信息
 * @param   int     $pay_id     支付方式id
 * @return  array   支付方式信息
 */
function payment_info($pay_id){
    $sql 	= 	'SELECT * FROM ' . 'ybr_payment' .
	            " WHERE pay_id = '$pay_id' AND enabled = 1";
	$datas	=	M()->query($sql);
    return empty($datas) ? array(): $datas[0];
}

/**
 * 取得团购活动信息
 * @param   int     $group_buy_id   团购活动id
 * @param   int     $current_num    本次购买数量（计算当前价时要加上的数量）
 * @return  array
 *                  status          状态：
 */
function group_buy_info($group_buy_id, $current_num = 0){
	$CommonModel		=	new CommonModel();
    /* 取得团购活动信息 */
    $group_buy_id = intval($group_buy_id);
    $sql = "SELECT *, act_id AS group_buy_id, act_desc AS group_buy_desc, start_time AS start_date, end_time AS end_date " .
            " FROM " . 'ybr_goods_activity' .
            " WHERE act_id = '$group_buy_id' " .
            " AND act_type = '" . GAT_GROUP_BUY . "'";
    //$group_buy = $GLOBALS['db']->getRow($sql);
    $group_buy	=	$CommonModel->getRow($sql);
    
    /* 如果为空，返回空数组 */
    if (empty($group_buy)){
        return array();
    }

    $ext_info 	= 	unserialize($group_buy['ext_info']);
    $group_buy	= 	array_merge($group_buy, $ext_info);
	
    /* 格式化时间 */
    $group_buy['formated_start_date'] 	= 	local_date('Y-m-d H:i', $group_buy['start_time']);
    $group_buy['formated_end_date'] 	= 	local_date('Y-m-d H:i', $group_buy['end_time']);

    /* 格式化保证金 */
    $group_buy['formated_deposit'] 		= 	price_format($group_buy['deposit'], false);

    /* 处理价格阶梯 */
    $price_ladder 						= 	$group_buy['price_ladder'];
    if (!is_array($price_ladder) || empty($price_ladder)){
        $price_ladder = array(array('amount' => 0, 'price' => 0));
    }
    else{
        foreach ($price_ladder as $key => $amount_price){
            $price_ladder[$key]['formated_price'] = price_format($amount_price['price'], false);
        }
    }
    $group_buy['price_ladder'] 	= 	$price_ladder;
    /* 统计信息 */
    $stat 						=	group_buy_stat($group_buy_id, $group_buy['deposit']);
    $group_buy 					= 	array_merge($group_buy, $stat);

    /* 计算当前价 */
    $cur_price  = $price_ladder[0]['price']; // 初始化
    $cur_amount = $stat['valid_goods'] + $current_num; // 当前数量
    foreach ($price_ladder as $amount_price)
    {
        if ($cur_amount >= $amount_price['amount'])
        {
            $cur_price = $amount_price['price'];
        }
        else
        {
            break;
        }
    }
    $group_buy['cur_price'] = $cur_price;
    $group_buy['formated_cur_price'] = price_format($cur_price, false);

    /* 最终价 */
    $group_buy['trans_price'] = $group_buy['cur_price'];
    $group_buy['formated_trans_price'] = $group_buy['formated_cur_price'];
    $group_buy['trans_amount'] = $group_buy['valid_goods'];

    /* 状态 */
    $group_buy['status'] = group_buy_status($group_buy);
    if (isset($GLOBALS['_LANG']['gbs'][$group_buy['status']]))
    {
        $group_buy['status_desc'] = $GLOBALS['_LANG']['gbs'][$group_buy['status']];
    }

    $group_buy['start_time'] = $group_buy['formated_start_date'];
    $group_buy['end_time'] = $group_buy['formated_end_date'];

    return $group_buy;
}

/*
 * 取得某团购活动统计信息
 * @param   int     $group_buy_id   团购活动id
 * @param   float   $deposit        保证金
 * @return  array   统计信息
 *                  total_order     总订单数
 *                  total_goods     总商品数
 *                  valid_order     有效订单数
 *                  valid_goods     有效商品数
 */
function group_buy_stat($group_buy_id, $deposit){
    $group_buy_id 	= 	intval($group_buy_id);
	$CommonModel	=	new CommonModel();
    
    /* 取得团购活动商品ID */
    $sql = "SELECT goods_id " .
           "FROM " . 'ybr_goods_activity' .
           "WHERE act_id = '$group_buy_id' " .
           "AND act_type = '" . GAT_GROUP_BUY . "'";
    //$group_buy_goods_id = $GLOBALS['db']->getOne($sql);    
    $group_buy_id	=	$CommonModel->getOne($sql);
    
    /* 取得总订单数和总商品数 */
    $sql 	= 	"SELECT COUNT(*) AS total_order, SUM(g.goods_number) AS total_goods " .
            	"FROM " . 'ybr_order_info' . " AS o, " .
                'ybr_order_goods' . " AS g " .
            	" WHERE o.order_id = g.order_id " .
            	"AND o.extension_code = 'group_buy' " .
            	"AND o.extension_id = '$group_buy_id' " .
            	"AND g.goods_id = '$group_buy_goods_id' " .
            	"AND (order_status = '" . OS_CONFIRMED . "' OR order_status = '" . OS_UNCONFIRMED . "')";    
    $stat 	= 	$CommonModel->getRow($sql);
    if ($stat['total_order'] == 0){
        $stat['total_goods'] = 0;
    }

    /* 取得有效订单数和有效商品数 */
    $deposit = floatval($deposit);
    if ($deposit > 0 && $stat['total_order'] > 0){
        $sql .= " AND (o.money_paid + o.surplus) >= '$deposit'";
        $row = $CommonModel->getRow($sql);
        $stat['valid_order'] = $row['total_order'];
        if ($stat['valid_order'] == 0){
            $stat['valid_goods'] = 0;
        }
        else{
            $stat['valid_goods'] = $row['total_goods'];
        }
    }
    else{
        $stat['valid_order'] = $stat['total_order'];
        $stat['valid_goods'] = $stat['total_goods'];
    }
    return $stat;
}

/**
 * 获得团购的状态
 *
 * @access  public
 * @param   array
 * @return  integer
 */
function group_buy_status($group_buy){
    $now = gmtime();
    if ($group_buy['is_finished'] == 0){
        /* 未处理 */
        if ($now < $group_buy['start_time']){
            $status = GBS_PRE_START;
        }
        elseif ($now > $group_buy['end_time']){
            $status = GBS_FINISHED;
        }
        else{
            if ($group_buy['restrict_amount'] == 0 || $group_buy['valid_goods'] < $group_buy['restrict_amount']){
                $status = GBS_UNDER_WAY;
            }
            else{
                $status = GBS_FINISHED;
            }
        }
    }
    elseif ($group_buy['is_finished'] == GBS_SUCCEED){
        /* 已处理，团购成功 */
        $status = GBS_SUCCEED;
    }
    elseif ($group_buy['is_finished'] == GBS_FAIL){
        /* 已处理，团购失败 */
        $status = GBS_FAIL;
    }
    return $status;
}

/**
 * 判断订单是否已发货（含部分发货）
 * @param   int     $order_id  订单 id
 * @return  int     1，已发货；0，未发货
 */
function order_deliveryed($order_id){
    $return_res = 0;
    if (empty($order_id)){
        return $return_res;
    }
    $sql = 'SELECT COUNT(delivery_id) FROM ' . 'ybr_delivery_order' . ' WHERE order_id = \''. $order_id . '\' AND status = 0';
    $CommonModel	=	new CommonModel();
    $sum = $CommonModel->getOne($sql);
    if ($sum){
        $return_res = 1;
    }
    return $return_res;
}



/**
 * 获取当前管理员信息
 *
 * @access  public
 * @param
 *
 * @return  Array
 */
function admin_info(){
	$CommonModel	=	new CommonModel();
    $sql = "SELECT * FROM ". 'ybr_admin_user'."
            WHERE user_id = '$_SESSION[admin_id]'
            LIMIT 0, 1";
    $admin_info = $CommonModel->getRow($sql);
    if (empty($admin_info)){
        return $admin_info = array();
    }
    return $admin_info;
}

/**
 * 取得发货单信息
 * @param   int     $delivery_order   发货单id（如果delivery_order > 0 就按id查，否则按sn查）
 * @param   string  $delivery_sn      发货单号
 * @return  array   发货单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function delivery_order_info($delivery_id, $delivery_sn = ''){
	
	$CommonModel	=	new CommonModel();
	
    $return_order = array();
    if (empty($delivery_id) || !is_numeric($delivery_id)){
        return $return_order;
    }

    $where = '';
    /* 获取管理员信息 */
    $admin_info = admin_info();

    /* 如果管理员属于某个办事处，只列出这个办事处管辖的发货单 */
    if ($admin_info['agency_id'] > 0){
        $where .= " AND agency_id = '" . $admin_info['agency_id'] . "' ";
    }

    /* 如果管理员属于某个供货商，只列出这个供货商的发货单 */
    if ($admin_info['suppliers_id'] > 0){
        $where .= " AND suppliers_id = '" . $admin_info['suppliers_id'] . "' ";
    }

    $sql = "SELECT * FROM " . 'ybr_delivery_order';
    if ($delivery_id > 0){
        $sql .= " WHERE delivery_id = '$delivery_id'";
    }
    else{
        $sql .= " WHERE delivery_sn = '$delivery_sn'";
    }

    $sql .= $where;
    $sql .= " LIMIT 0, 1";
    $delivery = $CommonModel->getRow($sql);
    if ($delivery){
        /* 格式化金额字段 */
        $delivery['formated_insure_fee']     = price_format($delivery['insure_fee'], false);
        $delivery['formated_shipping_fee']   = price_format($delivery['shipping_fee'], false);

        /* 格式化时间字段 */
        $delivery['formated_add_time']       = local_date("Y-m-d H:i:s", $delivery['add_time']);
        $delivery['formated_update_time']    = local_date("Y-m-d H:i:s", $delivery['update_time']);

        $return_order = $delivery;
    }
    return $return_order;
}



/**
 * 删除发货单时进行退货
 *
 * @access   public
 * @param    int     $delivery_id      发货单id
 * @param    array   $delivery_order   发货单信息数组
 *
 * @return  void
 */
function delivery_return_goods($delivery_id, $delivery_order){
	
    /* 查询：取得发货单商品 */
    $goods_sql = "SELECT * FROM " . 'ybr_delivery_goods' . " WHERE delivery_id = " . $delivery_order['delivery_id'];
    $goods_list = M()->query($goods_sql);
    /* 更新： */
    foreach ($goods_list as $key=>$val){
        $sql = "UPDATE " . 'ybr_order_goods' .
               " SET send_number = send_number-'".$goods_list[$key]['send_number']. "'".
               " WHERE order_id = '".$delivery_order['order_id']."' AND goods_id = '".$goods_list[$key]['goods_id']."' LIMIT 1";
        M()->query($sql);
    }
    $sql = "UPDATE " . 'ybr_order_info' .
           " SET shipping_status = '0' , order_status = 1".
           " WHERE order_id = '".$delivery_order['order_id']."' LIMIT 1";
    M()->query($sql);
}

/**
 * 删除发货单时删除其在订单中的发货单号
 *
 * @access   public
 * @param    int      $order_id              定单id
 * @param    string   $delivery_invoice_no   发货单号
 *
 * @return  void
 */
function del_order_invoice_no($order_id, $delivery_invoice_no){
	$CommonModel	=	new CommonModel();
    /* 查询：取得订单中的发货单号 */
    $sql = "SELECT invoice_no
            FROM " . 'ybr_order_info' . "
            WHERE order_id = '$order_id'";
    $order_invoice_no = $CommonModel->getOne($sql);

    /* 如果为空就结束处理 */
    if (empty($order_invoice_no)){
        return;
    }

    /* 去除当前发货单号 */
    $order_array = explode('<br>', $order_invoice_no);
    $delivery_array = explode('<br>', $delivery_invoice_no);

    foreach ($order_array as $key => $invoice_no){
        if ($ii = array_search($invoice_no, $delivery_array)){
            unset($order_array[$key], $delivery_array[$ii]);
        }
    }

    $arr['invoice_no'] = implode('<br>', $order_array);
    update_order($order_id, $arr);
}


/**
 * 修改订单
 * @param   int     $order_id   订单id
 * @param   array   $order      key => value
 * @return  bool
 */
function update_order($order_id, $order){
	$CommonModel	=	new CommonModel();    
    return $CommonModel->autoExecute('order_info',$order, 'UPDATE', "order_id = '$order_id'");
}

/**
 * 更新订单总金额
 * @param   int     $order_id   订单id
 * @return  bool
 */
function update_order_amount($order_id){
    //更新订单总金额
    $sql = "UPDATE " . 'ybr_order_info' .
            " SET order_amount = " . order_due_field() .
            " WHERE order_id = '$order_id' LIMIT 1";
    return M()->query($sql);
}

/**
 * 生成计算应付款金额的字段
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_due_field($alias = ''){
    return order_amount_field($alias) .
            " - {$alias}money_paid - {$alias}surplus - {$alias}integral_money" .
            " - {$alias}bonus - {$alias}discount ";
}


/**
 * 改变订单中商品库存
 * @param   int     $order_id  订单 id
 * @param   array   $_sended   Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $goods_list
 * @return  Bool
 */
function change_order_goods_storage_split($order_id, $_sended, $goods_list = array()){
    /* 参数检查 */
    if (!is_array($_sended) || empty($order_id)){
        return false;
    }

    foreach ($_sended as $key => $value){
        // 商品（超值礼包）
        if (is_array($value)){
            if (!is_array($goods_list)){
                $goods_list = array();
            }
            foreach ($goods_list as $goods){
                if (($key != $goods['rec_id']) || (!isset($goods['package_goods_list']) || !is_array($goods['package_goods_list']))){
                    continue;
                }

                // 超值礼包无库存，只减超值礼包商品库存
                foreach ($goods['package_goods_list'] as $package_goods){
                    if (!isset($value[$package_goods['goods_id']])){
                        continue;
                    }

                    // 减库存：商品（超值礼包）（实货）、商品（超值礼包）（虚货）
                    $sql = "UPDATE " . 'ybr_goods' ."
                            SET goods_number = goods_number - '" . $value[$package_goods['goods_id']] . "'
                            WHERE goods_id = '" . $package_goods['goods_id'] . "' ";
                    M()->query($sql);
                }
            }
        }
        // 商品（实货）
        elseif (!is_array($value)){
            /* 检查是否为商品（实货） */
            foreach ($goods_list as $goods){
                if ($goods['rec_id'] == $key && $goods['is_real'] == 1){
                    $sql = "UPDATE " . 'ybr_goods' . "
                            SET goods_number = goods_number - '" . $value . "'
                            WHERE goods_id = '" . $goods['goods_id'] . "' ";
                    M()->query($sql);
                    break;
                }
            }
        }
    }

    return true;
}

/**
 * 改变订单中商品库存
 * @param   int     $order_id   订单号
 * @param   bool    $is_dec     是否减少库存
 * @param   bool    $storage     减库存的时机，1，下订单时；0，发货时；
 */
function change_order_goods_storage($order_id, $is_dec = true, $storage = 0){
    /* 查询订单商品信息 */
    switch ($storage){
        case 0 :
            $sql = "SELECT goods_id, SUM(send_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . 'ybr_order_goods' .
                    " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
        break;

        case 1 :
            $sql = "SELECT goods_id, SUM(goods_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . 'ybr_order_goods' .
                    " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
        break;
    }
	
    $res = M()->query($sql);
    foreach($res as $row){
    	if ($row['extension_code'] != "package_buy"){
            if ($is_dec){// 减少库存
                change_goods_storage($row['goods_id'], $row['product_id'], - $row['num']);
            }
            else{// 增加库存
                change_goods_storage($row['goods_id'], $row['product_id'], $row['num']);
            }
            M()->query($sql);
        }
        else{
            $sql = "SELECT goods_id, goods_number" .
                   " FROM " . 'ybr_package_goods' .
                   " WHERE package_id = '" . $row['goods_id'] . "'";
            $res_goods = M()->query($sql);
            foreach($res_goods as $row_goods){
            	$sql = 	"SELECT is_real" .
                  	 	" FROM " . 'ybr_goods' .
                  	 	" WHERE goods_id = '" . $row_goods['goods_id'] . "'";
                $real_goods = M()->query($sql);
                $is_goods = $real_goods[0];

                if ($is_dec){
                    change_goods_storage($row_goods['goods_id'], $row['product_id'], - ($row['num'] * $row_goods['goods_number']));
                }
                elseif ($is_goods['is_real']){
                    change_goods_storage($row_goods['goods_id'], $row['product_id'], ($row['num'] * $row_goods['goods_number']));
                }
            }
        }
    }
}

/**
 * 商品库存增与减 货品库存增与减
 *
 * @param   int    $good_id         商品ID
 * @param   int    $product_id      货品ID
 * @param   int    $number          增减数量，默认0；
 *
 * @return  bool               true，成功；false，失败；
 */
function change_goods_storage($good_id, $product_id, $number = 0){
    if ($number == 0){
        return true; // 值为0即不做、增减操作，返回true
    }

    if (empty($good_id) || empty($number)){
        return false;
    }

    $number = ($number > 0) ? '+ ' . $number : $number;

    /* 处理货品库存 */
    $products_query = true;
    if (!empty($product_id)){
        $sql = "UPDATE " . 'ybr_products' ."
                SET product_number = product_number $number
                WHERE goods_id = '$good_id'
                AND product_id = '$product_id'
                LIMIT 1";
        $products_query = M()->query($sql);
    }

    /* 处理商品库存 */
    $sql = "UPDATE " . 'ybr_goods' ."
            SET goods_number = goods_number $number
            WHERE goods_id = '$good_id'
            LIMIT 1";
    $query = M()->query($sql);

    if ($query && $products_query){
        return true;
    }
    else{
        return false;
    }
}


/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   float   $frozen_money   冻结余额变动
 * @param   int     $rank_points    等级积分变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $change_desc    变动说明
 * @param   int     $change_type    变动类型：参见常量文件
 * @return  void
 */
function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = ACT_OTHER){
    
    $CommonModel	=	new CommonModel();
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'frozen_money'  => $frozen_money,
        'rank_points'   => $rank_points,
        'pay_points'    => $pay_points,
        'change_time'   => gmtime(),
        'change_desc'   => $change_desc,
        'change_type'   => $change_type
    );
    //$GLOBALS['db']->autoExecute('ybr_account_log'), $account_log, 'INSERT');
	$CommonModel->autoExecute('account_log', $account_log, 'INSERT');
    /* 更新用户信息 */
    $sql = "UPDATE " . 'ybr_users' .
            " SET user_money = user_money + ('$user_money')," .    	// 原来账户的金额加上返回的金额
            " frozen_money = frozen_money + ('$frozen_money')," .	// 冻结变动
            " rank_points = rank_points + ('$rank_points')," .		// 等级积分变动
            " pay_points = pay_points + ('$pay_points')" .			// 消费积分变动
            " WHERE user_id = '$user_id' LIMIT 1";					
    //$GLOBALS['db']->query($sql);
    M()->query($sql);
}

/**
 * 取得某订单应该赠送的积分数
 * @param   array   $order  订单
 * @return  int     积分数
 */
function integral_to_give($order){
	$CommonModel	=	new CommonModel();
    /* 判断是否团购 */
    if ($order['extension_code'] == 'group_buy'){
        $group_buy = group_buy_info(intval($order['extension_id']));
        return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']);
    }
    else{
        $sql = 	"SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " .
                "FROM " . 'ybr_order_goods' . " AS og, " .
                'ybr_goods' . " AS g " .
                "WHERE og.goods_id = g.goods_id " .
                "AND og.order_id = '$order[order_id]' " .
                "AND og.goods_id > 0 " .
                "AND og.parent_id = 0 " .
                "AND og.is_gift = 0 AND og.extension_code != 'package_buy'";

        return $CommonModel->getRow($sql);
    }
}

/**
 * 返回订单发放的红包
 * @param   int     $order_id   订单id
 */
function return_order_bonus($order_id){
	$OrderModel	=	new OrderModel();
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);

    /* 删除 */
    if ($bonus_list){
        /* 取得订单信息 */
        $order = $OrderModel->get_order_info($order_id);
        $user_id = $order['user_id'];

        foreach ($bonus_list AS $bonus){
            $sql = "DELETE FROM " . 'ybr_user_bonus' .
                    " WHERE bonus_type_id = '$bonus[type_id]' " .
                    "AND user_id = '$user_id' " .
                    "AND order_id = '0' LIMIT " . $bonus['number'];
            //$GLOBALS['db']->query($sql);
            M()->query($sql);
        }
    }
}

/**
 * 取得订单应该发放的红包
 * @param   int     $order_id   订单id
 * @return  array
 */
function order_bonus($order_id){
	$CommonModel	=	new CommonModel();
    /* 查询按商品发的红包 */
    $day    = getdate();
    $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql = "SELECT b.type_id, b.type_money, SUM(o.goods_number) AS number " .
            "FROM " . 'ybr_order_goods' . " AS o, " .
                      'ybr_goods' . " AS g, " .
                      'ybr_bonus_type' . " AS b " .
            " WHERE o.order_id = '$order_id' " .
            " AND o.is_gift = 0 " .
            " AND o.goods_id = g.goods_id " .
            " AND g.bonus_type_id = b.type_id " .
            " AND b.send_type = '" . SEND_BY_GOODS . "' " .
            " AND b.send_start_date <= '$today' " .
            " AND b.send_end_date >= '$today' " .
            " GROUP BY b.type_id ";
    
    $list = M()->query($sql);

    /* 查询定单中非赠品总金额 */
    $amount = order_amount($order_id, false);

    /* 查询订单日期 */
    $sql = "SELECT add_time " .
            " FROM " . 'ybr_order_info' .
            " WHERE order_id = '$order_id' LIMIT 1";
    $order_time = $CommonModel->getOne($sql);

    /* 查询按订单发的红包 */
    $sql = "SELECT type_id, type_money, IFNULL(FLOOR('$amount' / min_amount), 1) AS number " .
            "FROM " . 'ybr_bonus_type' .
            "WHERE send_type = '" . SEND_BY_ORDER . "' " .
            "AND send_start_date <= '$order_time' " .
            "AND send_end_date >= '$order_time' ";
    $list = array_merge($list, M()->query($sql));
    return $list;
}


/**
 * 取得订单总金额
 * @param   int     $order_id   订单id
 * @param   bool    $include_gift   是否包括赠品
 * @return  float   订单总金额
 */
function order_amount($order_id, $include_gift = true){
	$CommonModel	=	new CommonModel();
    $sql = "SELECT SUM(goods_price * goods_number) " .
            "FROM " . 'ybr_order_goods' .
            " WHERE order_id = '$order_id'";
    if (!$include_gift){
        $sql .= " AND is_gift = 0";
    }
    return floatval($CommonModel->getOne($sql));
}

/**
 * 删除发货单(不包括已退货的单子)
 * @param   int     $order_id  订单 id
 * @return  int     1，成功；0，失败
 */
function del_order_delivery($order_id){
    $return_res = 0;

    if (empty($order_id)){
        return $return_res;
    }
    $sql = 'DELETE O, G
            FROM ' . 'ybr_delivery_order' . ' AS O, ' . 'ybr_delivery_goods' . ' AS G
            WHERE O.order_id = \'' . $order_id . '\'
            AND O.status = 0
            AND O.delivery_id = G.delivery_id';
    $query = M()->query($sql);
    
    if ($query){
        $return_res = 1;
    }
    return $return_res;
}


/**
 * 退回余额、积分、红包（取消、无效、退货时），把订单使用余额、积分、红包设为0
 * @param   array   $order  订单信息
 */
function return_user_surplus_integral_bonus($order){
    /* 处理余额、积分、红包 */
    if ($order['user_id'] > 0 && $order['surplus'] > 0){
        $surplus = $order['money_paid'] < 0 ? $order['surplus'] + $order['money_paid'] : $order['surplus'];
        log_account_change($order['user_id'], $surplus, 0, 0, 0, sprintf(L('return_order_surplus'), $order['order_sn']));
        M()->query("UPDATE ". 'ybr_order_info' . " SET `order_amount` = '0' WHERE `order_id` =". $order['order_id']);
    }

    if ($order['user_id'] > 0 && $order['integral'] > 0){
        log_account_change($order['user_id'], 0, 0, 0, $order['integral'], sprintf(L('return_order_integral'), $order['order_sn']));
    }
	/* 设置红包未使用 */ 
    if ($order['bonus_id'] > 0){
        unuse_bonus($order['bonus_id']);
    }

    /* 修改订单 */
    $arr = array(
        'bonus_id'  => 0,
        'bonus'     => 0,
        'integral'  => 0,
        'integral_money'    => 0,
        'surplus'   => 0
    );
    update_order($order['order_id'], $arr);
}

/**
 * 设置红包为未使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function unuse_bonus($bonus_id){
    $sql = "UPDATE " . 'ybr_user_bonus' .
            " SET order_id = 0, used_time = 0 " .
            "WHERE bonus_id = '$bonus_id' LIMIT 1";
    return  M()->query($sql);
}



/**
 *  获取发货单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function get_delivery_list(){
        $aiax = isset($_GET['is_ajax']) ? $_GET['is_ajax'] : 0;
        /* 过滤信息 */
        $filter['delivery_sn'] = empty($_REQUEST['delivery_sn']) ? '' : trim($_REQUEST['delivery_sn']);
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['order_id'] = empty($_REQUEST['order_id']) ? 0 : intval($_REQUEST['order_id']);
        if ($aiax == 1 && !empty($_REQUEST['consignee'])){
            $_REQUEST['consignee'] = $_REQUEST['consignee'];
        }
        $filter['consignee'] = empty($_REQUEST['consignee']) ? '' : trim($_REQUEST['consignee']);
        $filter['status'] = isset($_REQUEST['status']) ? $_REQUEST['status'] : -1;

        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'update_time' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn']){
            $where .= " AND order_sn LIKE '%" . Utils::mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['consignee']){
            $where .= " AND consignee LIKE '%" . Utils::mysql_like_quote($filter['consignee']) . "%'";
        }
        if ($filter['status'] >= 0){
            $where .= " AND status = '" . Utils::mysql_like_quote($filter['status']) . "'";
        }
        if ($filter['delivery_sn']){
            $where .= " AND delivery_sn LIKE '%" . Utils::mysql_like_quote($filter['delivery_sn']) . "%'";
        }

        /* 获取管理员信息 */
        $admin_info = admin_info();

        /* 如果管理员属于某个办事处，只列出这个办事处管辖的发货单 */
        if ($admin_info['agency_id'] > 0){
            $where .= " AND agency_id = '" . $admin_info['agency_id'] . "' ";
        }

        /* 如果管理员属于某个供货商，只列出这个供货商的发货单 */
        if ($admin_info['suppliers_id'] > 0){
            $where .= " AND suppliers_id = '" . $admin_info['suppliers_id'] . "' ";
        }

        /* 查询 */
        $sql = "SELECT delivery_id, delivery_sn, order_sn, order_id, add_time, action_user, consignee, country,
                       province, city, district, tel, status, update_time, email, suppliers_id
                FROM " . "ybr_delivery_order" . " $where
                ORDER BY " . $filter['sort_by'] . " " . $filter['sort_order'];
    return $sql;
}


/**
 * 超级礼包发货数处理
 * @param   array   超级礼包商品列表
 * @param   int     发货数量
 * @param   int     订单ID
 * @param   varchar 虚拟代码
 * @param   int     礼包ID
 * @return  array   格式化结果
 */
function package_goods(&$package_goods, $goods_number, $order_id, $extension_code, $package_id){
    $return_array = array();

    if (count($package_goods) == 0 || !is_numeric($goods_number)){
        return $return_array;
    }

    foreach ($package_goods as $key=>$value){
        $return_array[$key] = $value;
        $return_array[$key]['order_send_number'] = $value['order_goods_number'] * $goods_number;
        $return_array[$key]['sended'] = package_sended($package_id, $value['goods_id'], $order_id, $extension_code, $value['product_id']);
        $return_array[$key]['send'] = ($value['order_goods_number'] * $goods_number) - $return_array[$key]['sended'];
        $return_array[$key]['storage'] = $value['goods_number'];


        if ($return_array[$key]['send'] <= 0)
        {
            $return_array[$key]['send'] = L('act_good_delivery');
            $return_array[$key]['readonly'] = 'readonly="readonly"';
        }

        /* 是否缺货 */
        //if ($return_array[$key]['storage'] <= 0 && $GLOBALS['_CFG']['use_storage'] == '1'){
        if ($return_array[$key]['storage'] <= 0){
            $return_array[$key]['send'] = L('act_good_vacancy');
            $return_array[$key]['readonly'] = 'readonly="readonly"';
        }
    }

    return $return_array;
}

/**
 * 获取超级礼包商品已发货数
 *
 * @param       int         $package_id         礼包ID
 * @param       int         $goods_id           礼包的产品ID
 * @param       int         $order_id           订单ID
 * @param       varchar     $extension_code     虚拟代码
 * @param       int         $product_id         货品id
 *
 * @return  int     数值
 */
function package_sended($package_id, $goods_id, $order_id, $extension_code, $product_id = 0){
	$CommonModel	=	new CommonModel();
    if (empty($package_id) || empty($goods_id) || empty($order_id) || empty($extension_code)){
        return false;
    }
    $sql = "SELECT SUM(DG.send_number)
            FROM " . 'ybr_delivery_goods' . " AS DG, " . 'ybr_delivery_order' . " AS o
            WHERE o.delivery_id = DG.delivery_id
            AND o.status IN (0, 2)
            AND o.order_id = '$order_id'
            AND DG.parent_id = '$package_id'
            AND DG.goods_id = '$goods_id'
            AND DG.extension_code = '$extension_code'";
    $sql .= ($product_id > 0) ? " AND DG.product_id = '$product_id'" : '';
    $send = $CommonModel->getOne($sql);
    return empty($send) ? 0 : $send;
}

/**
 * 供货商列表信息
 *
 * @param       string      $conditions
 * @return      array
 */
function suppliers_list_info($conditions = '')
{
    $where = '';
    if (!empty($conditions))
    {
        $where .= 'WHERE ';
        $where .= $conditions;
    }

    /* 查询 */
    $sql = "SELECT suppliers_id, suppliers_name, suppliers_desc
            FROM " . "ybr_suppliers" . "
            $where";

    return M()->query($sql);
}

/**
 * 供货商名
 *
 * @return  array
 */
function suppliers_list_name(){
    /* 查询 */
    $suppliers_list = suppliers_list_info(' is_check = 1 ');

    /* 供货商名字 */
    $suppliers_name = array();
    if (count($suppliers_list) > 0){
        foreach ($suppliers_list as $suppliers){
            $suppliers_name[$suppliers['suppliers_id']] = $suppliers['suppliers_name'];
        }
    }
    return $suppliers_name;
}

// 回调函数：并递归
function trim_array_walk(&$array_value){
    if (is_array($array_value)){
        array_walk($array_value, 'trim_array_walk');
    }else{
        $array_value = trim($array_value);
    }
}

function intval_array_walk(&$array_value){
    if (is_array($array_value)){
        array_walk($array_value, 'intval_array_walk');
    }else{
        $array_value = intval($array_value);
    }
}

/**
 * 得到新发货单号
 * @return  string
 */
function get_delivery_sn(){
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
    return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 更新订单虚拟商品信息
 * @param   int     $order_id       订单 id
 * @param   array   $_sended        Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $virtual_goods  虚拟商品列表
 * @return  Bool
 */
function update_order_virtual_goods($order_id, $_sended, $virtual_goods){
    if (!is_array($_sended) || empty($order_id)){
        return false;
    }
    if (empty($virtual_goods)){
        return true;
    }
    elseif (!is_array($virtual_goods)){
        return false;
    }

    foreach ($virtual_goods as $goods){
        $sql = "UPDATE ". 'ybr_order_goods'. "
                SET send_number = send_number + '" . $goods['num'] . "'
                WHERE order_id = '" . $order_id . "'
                AND goods_id = '" . $goods['goods_id'] . "' ";
        if (!M()->query($sql)){
            return false;
        }
    }
    return true;
}

/**
 * 更新订单商品信息
 * @param   int     $order_id       订单 id
 * @param   array   $_sended        Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $goods_list
 * @return  Bool
 */
function update_order_goods($order_id, $_sended, $goods_list = array()){
    if (!is_array($_sended) || empty($order_id)){
        return false;
    }
    foreach ($_sended as $key => $value){
        // 超值礼包
        if (is_array($value)){
            if (!is_array($goods_list)){
                $goods_list = array();
            }
            foreach ($goods_list as $goods){
                if (($key != $goods['rec_id']) || (!isset($goods['package_goods_list']) || !is_array($goods['package_goods_list']))){
                    continue;
                }
                $goods['package_goods_list'] = package_goods($goods['package_goods_list'], $goods['goods_number'], $goods['order_id'], $goods['extension_code'], $goods['goods_id']);
                $pg_is_end = true;

                foreach ($goods['package_goods_list'] as $pg_key => $pg_value){
                    if ($pg_value['order_send_number'] != $pg_value['sended']){
                        $pg_is_end = false; // 此超值礼包，此商品未全部发货
                        break;
                    }
                }
                // 超值礼包商品全部发货后更新订单商品库存
                if ($pg_is_end){
                    $sql = "UPDATE " . 'ybr_order_goods' . "
                            SET send_number = goods_number
                            WHERE order_id = '$order_id'
                            AND goods_id = '" . $goods['goods_id'] . "' ";
                   M()->query($sql);
                }
            }
        }
        // 商品（实货）（货品）
        elseif (!is_array($value)){
            /* 检查是否为商品（实货）（货品） */
            foreach ($goods_list as $goods){
                if ($goods['rec_id'] == $key && $goods['is_real'] == 1){
                    $sql = "UPDATE " . 'ybr_order_goods' . "
                            SET send_number = send_number + $value
                            WHERE order_id = '$order_id'
                            AND rec_id = '$key' ";
                    M()->query($sql);
                    break;
                }
            }
        }
    }
    return true;
}

/**
 * 订单单个商品或货品的已发货数量
 *
 * @param   int     $order_id       订单 id
 * @param   int     $goods_id       商品 id
 * @param   int     $product_id     货品 id
 *
 * @return  int
 */
function order_delivery_num($order_id, $goods_id, $product_id = 0){
	$CommonModel	=	new CommonModel();
    $sql = 'SELECT SUM(G.send_number) AS sums
            FROM ' . 'ybr_delivery_goods' . ' AS G, ' . 'ybr_delivery_order' . ' AS O
            WHERE O.delivery_id = G.delivery_id
            AND O.status = 0
            AND O.order_id = ' . $order_id . '
            AND G.extension_code <> "package_buy"
            AND G.goods_id = ' . $goods_id;

    $sql .= ($product_id > 0) ? " AND G.product_id = '$product_id'" : '';
    $sum = $CommonModel->getOne($sql);
    if (empty($sum)){
        $sum = 0;
    }
    return $sum;
}

/**
 * 订单中的商品是否已经全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货
 */
function get_order_finish($order_id){
	$CommonModel	=	new CommonModel();
    $return_res = 0;
    if (empty($order_id)){
        return $return_res;
    }
    $sql = 'SELECT COUNT(rec_id)
            FROM ' . 'ybr_order_goods' . '
            WHERE order_id = \'' . $order_id . '\'
            AND goods_number > send_number';

    $sum = $CommonModel->getOne($sql);
    if (empty($sum)){
        $return_res = 1;
    }
    return $return_res;
}


/**
 *  虚拟卡发货
 *
 * @access  public
 * @param   string      $goods      商品详情数组
 * @param   string      $order_sn   本次操作的订单
 * @param   string      $msg        返回信息
 * @param   string      $process    设定当前流程：split，发货分单流程；other，其他，默认。
 *
 * @return  boolen
 */
function virtual_card_shipping ($goods, $order_sn, &$msg, $process = 'other'){
    /* 包含加密解密函数所在文件 */
    //include_once(ROOT_PATH . 'includes/lib_code.php');
    $CommonModel	=	new CommonModel();

    /* 检查有没有缺货 */
    $sql 			= 	"SELECT COUNT(*) FROM ".'ybr_virtual_card' . " WHERE goods_id = '$goods[goods_id]' AND is_saled = 0 ";
    $num 			= 	$CommonModel->GetOne($sql);

    if ($num < $goods['num']){
        $msg 		.= 	sprintf(L('virtual_card_oos'), $goods['goods_name']);
        return false;
    }

     /* 取出卡片信息 */
     $sql 			= 	"SELECT card_id, card_sn, card_password, end_date, crc32 FROM ".'ybr_virtual_card' . " WHERE goods_id = '$goods[goods_id]' AND is_saled = 0  LIMIT " . $goods['num'];
     $arr 			= 	$CommonModel->query($sql);

     $card_ids 		= 	array();
     $cards 		= 	array();

     foreach ($arr as $virtual_card){
        $card_info = array();

        /* 卡号和密码解密 */
        if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY)){
            $card_info['card_sn'] = decrypt($virtual_card['card_sn']);
            $card_info['card_password'] = decrypt($virtual_card['card_password']);
        }
        elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY)){
            $card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
            $card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
        }
        else{
            $msg .= 'error key';

            return false;
        }
        $card_info['end_date'] 	= 	date("Y-m-d H:i:s", $virtual_card['end_date']);
        $card_ids[] 			= 	$virtual_card['card_id'];
        $cards[] 				= 	$card_info;
     }

     /* 标记已经取出的卡片 */
    $sql = "UPDATE " . ' ybr_virtual_card ' . " SET " . "is_saled = 1 ," . "order_sn = '$order_sn' " . "WHERE " . db_create_in($card_ids, 'card_id');
    if (!$CommonModel->query($sql)){
        $msg .= $CommonModel->getError();
        return false;
    }

    /* 更新库存 */
    $sql = "UPDATE ".'ybr_goods'. " SET goods_number = goods_number - '$goods[num]' WHERE goods_id = '$goods[goods_id]'";
    M()->query($sql);

    if (true){
        /* 获取订单信息 */
        $sql = "SELECT order_id, order_sn, consignee, email FROM ".'ybr_order_info' . " WHERE order_sn = '$order_sn'";
        $order = $CommonModel->GetRow($sql);

        /* 更新订单信息 */
        if ($process == 'split'){
            $sql = "UPDATE ".'ybr_order_goods'. "
                    SET send_number = send_number + '" . $goods['num'] . "'
                    WHERE order_id = '" . $order['order_id'] . "'
                    AND goods_id = '" . $goods['goods_id'] . "' ";
        }
        else{
            $sql = "UPDATE ".'ybr_order_goods'. "
                    SET send_number = '" . $goods['num'] . "'
                    WHERE order_id = '" . $order['order_id'] . "'
                    AND goods_id = '" . $goods['goods_id'] . "' ";
        }

        if (!$CommonModel->query($sql, 'SILENT')){
            $msg .= $CommonModel->getError();
            return false;
        }
    }

//    /* 发送邮件 */
//    $GLOBALS['smarty']->assign('virtual_card',                   $cards);
//    $GLOBALS['smarty']->assign('order',                          $order);
//    $GLOBALS['smarty']->assign('goods',                          $goods);
//
//    $GLOBALS['smarty']->assign('send_time', date('Y-m-d H:i:s'));
//    $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
//    $GLOBALS['smarty']->assign('send_date', date('Y-m-d'));
//    $GLOBALS['smarty']->assign('sent_date', date('Y-m-d'));
//
//    $tpl = get_mail_template('virtual_card');
//    $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
//    send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);

    return true;
}


/**
 * 判断订单的发货单是否全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货；-1，部分发货；-2，完全没发货；
 */
function get_all_delivery_finish($order_id){
    $return_res = 0;
    $CommonModel	=	new CommonModel();

    if (empty($order_id)){
        return $return_res;
    }

    /* 未全部分单 */
    if (!get_order_finish($order_id)){
        return $return_res;
    }
    /* 已全部分单 */
    else{
        // 是否全部发货
        $sql = "SELECT COUNT(delivery_id)
                FROM " . 'ybr_delivery_order' . "
                WHERE order_id = '$order_id'
                AND status = 2 ";
        $sum = $CommonModel->getOne($sql);
        // 全部发货
        if (empty($sum)){
            $return_res = 1;
        }
        // 未全部发货
        else{
            /* 订单全部发货中时：当前发货单总数 */
            $sql	= 	"SELECT COUNT(delivery_id)
	            		FROM " . 'ybr_delivery_order' . "
            			WHERE order_id = '$order_id'
            			AND status <> 1 ";
            $_sum 	= 	$CommonModel->getOne($sql);
            if ($_sum == $sum){
                $return_res = -2; // 完全没发货
            }
            else{
                $return_res = -1; // 部分发货
            }
        }
    }
    return $return_res;
}


/**
 * 记录订单操作记录
 *
 * @access  public
 * @param   string  $order_sn           订单编号
 * @param   integer $order_status       订单状态
 * @param   integer $shipping_status    配送状态
 * @param   integer $pay_status         付款状态
 * @param   string  $note               备注
 * @param   string  $username           用户名，用户自己的操作则为 buyer
 * @return  void
 */
function order_action($order_sn, $order_status, $shipping_status, $pay_status, $note = '', $username = null, $place = 0){
    if (is_null($username)){
        $username = $_SESSION['admin_name'];
    }
    $sql = 'INSERT INTO ' . 'ybr_order_action' .
                ' (order_id, action_user, order_status, shipping_status, pay_status, action_place, action_note, log_time) ' .
            'SELECT ' .
                "order_id, '$username', '$order_status', '$shipping_status', '$pay_status', '$place', '$note', '" .gmtime() . "' " .
            'FROM ' . 'ybr_order_info' . " WHERE order_sn = '$order_sn'";
    M()->query($sql);
}


/**
 * 发红包：发货时发红包
 * @param   int     $order_id   订单号
 * @return  bool
 */
function send_order_bonus($order_id){
    /* 取得订单应该发放的红包 */
    $bonus_list = order_bonus($order_id);
    $CommonModel	=	new CommonModel();

    /* 如果有红包，统计并发送 */
    if ($bonus_list){
        /* 用户信息 */
        $sql = "SELECT u.user_id, u.user_name, u.email " .
                "FROM " . 'ybr_order_info' . " AS o, " .
                          'ybr_users' . " AS u " .
                "WHERE o.order_id = '$order_id' " .
                "AND o.user_id = u.user_id ";
        $user = $CommonModel->getRow($sql);

        /* 统计 */
        $count = 0;
        $money = '';
        foreach ($bonus_list AS $bonus){
            $count += $bonus['number'];
            $money .= price_format($bonus['type_money']) . ' [' . $bonus['number'] . '], ';

            /* 修改用户红包 */
            $sql = "INSERT INTO " . 'ybr_user_bonus' . " (bonus_type_id, user_id) " .
                    "VALUES('$bonus[type_id]', '$user[user_id]')";
            for ($i = 0; $i < $bonus['number']; $i++){
                if (!$CommonModel->query($sql)){
                    return $CommonModel->getError();
                }
            }
        }

        /* 如果有红包，发送邮件 
        if ($count > 0){
            $tpl = get_mail_template('send_bonus');
            $GLOBALS['smarty']->assign('user_name', $user['user_name']);
            $GLOBALS['smarty']->assign('count', $count);
            $GLOBALS['smarty']->assign('money', $money);
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', local_date($GLOBALS['_CFG']['date_format']));
            $GLOBALS['smarty']->assign('sent_date', local_date($GLOBALS['_CFG']['date_format']));
            $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
            send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']);
        }*/
    }

    return true;
}



/**
 * 取得订单信息
 * @param   int     $order_id   订单id（如果order_id > 0 就按id查，否则按sn查）
 * @param   string  $order_sn   订单号
 * @return  array   订单信息（金额都有相应格式化的字段，前缀是formated_）
 */
function order_info($order_id, $order_sn = ''){
	$CommonModel	=	new CommonModel();
    /* 计算订单各种费用之和的语句 */
    $total_fee 	= 	" (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee ";
    $order_id 	= 	intval($order_id);
    if ($order_id > 0){
        $sql 	= 	"SELECT *, " . $total_fee . " FROM " . 'ybr_order_info' .
                	" WHERE order_id = '$order_id'";
    }
    else{
        $sql	= 	"SELECT *, " . $total_fee . "  FROM " . 'ybr_order_info' .
                	" WHERE order_sn = '$order_sn'";
    }
    // 测试
    //echo  $sql;
    
    $order 		= 	$CommonModel->getRow($sql);

    /* 格式化金额字段 */
    if ($order){
        $order['formated_goods_amount']   = price_format($order['goods_amount'], false);
        $order['formated_discount']       = price_format($order['discount'], false);
        $order['formated_tax']            = price_format($order['tax'], false);
        $order['formated_shipping_fee']   = price_format($order['shipping_fee'], false);
        $order['formated_insure_fee']     = price_format($order['insure_fee'], false);
        $order['formated_pay_fee']        = price_format($order['pay_fee'], false);
        $order['formated_pack_fee']       = price_format($order['pack_fee'], false);
        $order['formated_card_fee']       = price_format($order['card_fee'], false);
        $order['formated_total_fee']      = price_format($order['total_fee'], false);
        $order['formated_money_paid']     = price_format($order['money_paid'], false);
        $order['formated_bonus']          = price_format($order['bonus'], false);
        $order['formated_integral_money'] = price_format($order['integral_money'], false);
        $order['formated_surplus']        = price_format($order['surplus'], false);
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
        $order['formated_add_time']       = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
    }
    return $order;
}

/**
 * 合并订单
 * @param   string  $from_order_sn  从订单号
 * @param   string  $to_order_sn    主订单号
 * @return  成功返回true，失败返回错误信息
 */
function merge_order($from_order_sn, $to_order_sn){
    /* 订单号不能为空 */
    if (trim($from_order_sn) == '' || trim($to_order_sn) == ''){
        return L('order_sn_not_null');
    }

    /* 订单号不能相同 */
    if ($from_order_sn == $to_order_sn){
        return L('two_order_sn_same');
    }

    /* 取得订单信息 */
    $from_order = order_info(0, $from_order_sn);
    $to_order   = order_info(0, $to_order_sn);

    t($from_order);
    t($to_order);
    
    
    /* 检查订单是否存在 */
    if (!$from_order){
        return sprintf(L('order_not_exist'), $from_order_sn);
    }
    elseif (!$to_order){
        return sprintf(L('order_not_exist'), $to_order_sn);
    }

    /* 检查合并的订单是否为普通订单，非普通订单不允许合并 */
    if ($from_order['extension_code'] != '' || $to_order['extension_code'] != 0){
        return L('merge_invalid_order');
    }

    /* 检查订单状态是否是已确认或未确认、未付款、未发货 */
    if ($from_order['order_status'] != OS_UNCONFIRMED && $from_order['order_status'] != OS_CONFIRMED){
        return sprintf(L('os_not_unconfirmed_or_confirmed', $from_order_sn) );
    }
    elseif ($from_order['pay_status'] != PS_UNPAYED){
        return sprintf( L('ps_not_unpayed'), $from_order_sn);
    }
    elseif ($from_order['shipping_status'] != SS_UNSHIPPED){
        return sprintf( L('ss_not_unshipped'), $from_order_sn);
    }

    if ($to_order['order_status'] != OS_UNCONFIRMED && $to_order['order_status'] != OS_CONFIRMED){
        return sprintf( L('os_not_unconfirmed_or_confirmed'), $to_order_sn);
    }
    elseif ($to_order['pay_status'] != PS_UNPAYED){
        return sprintf( L('ps_not_unpayed'), $to_order_sn);
    }
    elseif ($to_order['shipping_status'] != SS_UNSHIPPED){
        return sprintf( L('ss_not_unshipped'), $to_order_sn);
    }

    /* 检查订单用户是否相同 */
    if ($from_order['user_id'] != $to_order['user_id']){
        return  L('order_user_not_same');
    }

    /* 合并订单 */
    $order 				= 	$to_order;
    $order['order_id']  = 	'';
    $order['add_time']  = 	gmtime();

    // 合并商品总额
    $order['goods_amount'] 	+= 	$from_order['goods_amount'];

    // 合并折扣
    $order['discount'] 		+= 	$from_order['discount'];

    if ($order['shipping_id'] > 0){
        // 重新计算配送费用
        $weight_price       = order_weight_price($to_order['order_id']);
        $from_weight_price  = order_weight_price($from_order['order_id']);
        $weight_price['weight'] += $from_weight_price['weight'];
        $weight_price['amount'] += $from_weight_price['amount'];
        $weight_price['number'] += $from_weight_price['number'];

        $region_id_list 	= 	array($order['country'], $order['province'], $order['city'], $order['district']);
        $shipping_area 		= 	shipping_area_info($order['shipping_id'], $region_id_list);

        $order['shipping_fee'] = shipping_fee($shipping_area['shipping_code'],
            unserialize($shipping_area['configure']), $weight_price['weight'], $weight_price['amount'], $weight_price['number']);

        // 如果保价了，重新计算保价费
        if ($order['insure_fee'] > 0){
            $order['insure_fee'] = shipping_insure_fee($shipping_area['shipping_code'], $order['goods_amount'], $shipping_area['insure']);
        }
    }

    // 重新计算包装费、贺卡费
    if ($order['pack_id'] > 0){
        $pack = pack_info($order['pack_id']);
        $order['pack_fee'] = $pack['free_money'] > $order['goods_amount'] ? $pack['pack_fee'] : 0;
    }
    if ($order['card_id'] > 0){
        $card = card_info($order['card_id']);
        $order['card_fee'] = $card['free_money'] > $order['goods_amount'] ? $card['card_fee'] : 0;
    }

    // 红包不变，合并积分、余额、已付款金额
    $order['integral']      += $from_order['integral'];
    $order['integral_money'] = value_of_integral($order['integral']);
    $order['surplus']       += $from_order['surplus'];
    $order['money_paid']    += $from_order['money_paid'];

    // 计算应付款金额（不包括支付费用）
    $order['order_amount'] = $order['goods_amount'] - $order['discount']
                           + $order['shipping_fee']
                           + $order['insure_fee']
                           + $order['pack_fee']
                           + $order['card_fee']
                           - $order['bonus']
                           - $order['integral_money']
                           - $order['surplus']
                           - $order['money_paid'];

    // 重新计算支付费
    if ($order['pay_id'] > 0){
        // 货到付款手续费
        $cod_fee          	= 	$shipping_area ? $shipping_area['pay_fee'] : 0;
        $order['pay_fee'] 	= 	pay_fee($order['pay_id'], $order['order_amount'], $cod_fee);

        // 应付款金额加上支付费
        $order['order_amount'] += $order['pay_fee'];
    }
	
    
    $CommonModel			=	new CommonModel();
    $order['order_sn'] 		= 	get_order_sn();
    /* 插入订单表 */
	if ($CommonModel->autoExecute('order_info', addslashes_deep($order), 'INSERT')){
        break;
    }
    else{
        if ($CommonModel->getError()){
            die($CommonModel->getDbError());
        }
    }    
    /*
    do{
        $order['order_sn'] 	= 	get_order_sn();
        if ($CommonModel->autoExecute('order_info', addslashes_deep($order), 'INSERT')){
            break;
        }
        else{
            if ($CommonModel->getDbError()){
                die($GLOBALS['db']->errorMsg());
            }
        }
    }
    while (true); // 防止订单号重复*/

    /* 订单号 */
    $order_id = $CommonModel->insert_id();
    
    /* 更新订单商品 */
    $sql = 'UPDATE ' . 'ybr_order_goods' .
            " SET order_id = '$order_id' " .
            "WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    M()->query($sql);

    //include_once(ROOT_PATH . 'includes/lib_clips.php');
    /* 插入支付日志 */
    insert_pay_log($order_id, $order['order_amount'], PAY_ORDER);

    /* 删除原订单 */
    $sql = 'DELETE FROM ' . 'ybr_order_info' .
            " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    $CommonModel->query($sql);

    /* 删除原订单支付日志 */
    $sql = 'DELETE FROM ' . 'ybr_pay_log' .
            " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id']));
    M()->query($sql);

    /* 返还 from_order 的红包，因为只使用 to_order 的红包 */
    if ($from_order['bonus_id'] > 0){
        unuse_bonus($from_order['bonus_id']);
    }

    /* 返回成功 */
    return true;
}

/**
 * 计算运费
 * @param   string  $shipping_code      配送方式代码
 * @param   mix     $shipping_config    配送方式配置信息
 * @param   float   $goods_weight       商品重量
 * @param   float   $goods_amount       商品金额
 * @param   float   $goods_number       商品数量
 * @return  float   运费
 */
function shipping_fee($shipping_code, $shipping_config, $goods_weight, $goods_amount, $goods_number=''){
    if (!is_array($shipping_config)){
        $shipping_config = unserialize($shipping_config);
    }
    Vendor('Shipping.' . $shipping_code);
	if(class_exists($shipping_code)){
		$obj 	= 	new $shipping_code($shipping_config);
		return $obj->calculate($goods_weight, $goods_amount, $goods_number);
	}
	else{
		return 0;	
	}
}


/**
 * 取得某配送方式对应于某收货地址的区域信息
 * @param   int     $shipping_id        配送方式id
 * @param   array   $region_id_list     收货人地区id数组
 * @return  array   配送区域信息（config 对应着反序列化的 configure）
 */
function shipping_area_info($shipping_id, $region_id_list){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'SELECT s.shipping_code, s.shipping_name, ' .
                		's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            			'FROM ' . 'ybr_shipping' . ' AS s, ' .
                		'ybr_shipping_area' . ' AS a, ' .
                		'ybr_area_region' . ' AS r ' .
            			"WHERE s.shipping_id = '$shipping_id' " .
            			'AND r.region_id ' . db_create_in($region_id_list) .
            			' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1';
    $row = $CommonModel->getRow($sql);

    if (!empty($row)){
        $shipping_config = unserialize_config($row['configure']);
        if (isset($shipping_config['pay_fee'])){
            if (strpos($shipping_config['pay_fee'], '%') !== false){
                $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
            }
            else{
                 $row['pay_fee'] = floatval($shipping_config['pay_fee']);
            }
        }
        else{
            $row['pay_fee'] = 0.00;
        }
    }
    return $row;
}

/**
 * 处理序列化的支付、配送的配置参数
 * 返回一个以name为索引的数组
 *
 * @access  public
 * @param   string       $cfg
 * @return  void
 */
function unserialize_config($cfg){
    if (is_string($cfg) && ($arr = unserialize($cfg)) !== false){
        $config = array();
        foreach ($arr AS $key => $val){
            $config[$val['name']] = $val['value'];
        }
        return $config;
    }
    else{
        return false;
    }
}

/**
 * 取得某订单商品总重量和总金额（对应 cart_weight_price）
 * @param   int     $order_id   订单id
 * @return  array   ('weight' => **, 'amount' => **, 'formated_weight' => **)
 */
function order_weight_price($order_id){
	$CommonModel	=	new CommonModel();
    $sql 			= 	"SELECT SUM(g.goods_weight * o.goods_number) AS weightformated_weight, " .
                		"SUM(o.goods_price * o.goods_number) AS amount ," .
                		"SUM(o.goods_number) AS number " .
            			"FROM " . 'ybr_order_goods' . " AS o, " .
                		'ybr_goods' . " AS g " .
            			"WHERE o.order_id = '$order_id' " .
            			"AND o.goods_id = g.goods_id";

    $row 			= 	$CommonModel->getRow($sql);
    $row['weight'] 	= 	floatval($row['weight']);
    $row['amount'] 	= 	floatval($row['amount']);
    $row['number'] 	= 	intval($row['number']);

    /* 格式化重量 */
    $row['formated_weight'] = formated_weight($row['weight']);
    return $row;
}



/**
 * 获取指定配送的保价费用
 *
 * @access  public
 * @param   string      $shipping_code  配送方式的code
 * @param   float       $goods_amount   保价金额
 * @param   mix         $insure         保价比例
 * @return  float
 */
function shipping_insure_fee($shipping_code, $goods_amount, $insure){

    if (strpos($insure, '%') === false){
        /* 如果保价费用不是百分比则直接返回该数值 */
        return floatval($insure);
    }
    else{
    	// 导入shipping插件
		Vendor('Shipping.' . $shipping_code);
		
		if(class_exists($shipping_code)){			
			 $shipping 	= 	new $shipping_code;
			 $insure   	= 	floatval($insure) / 100;
			 
			if (method_exists($shipping, 'calculate_insure')){
                return $shipping->calculate_insure($goods_amount, $insure);
            }
            else{
                return ceil($goods_amount * $insure);
            }
		}
		else{
			 return false;
		}
    }
}

/**
 * 取得包装信息
 * @param   int     $pack_id    包装id
 * @return  array   包装信息
 */
function pack_info($pack_id){
	$CommonModel	=	new CommonModel();
    $sql 			= 	"SELECT * FROM " . 'ybr_pack' . " WHERE pack_id = '$pack_id'";
    return $CommonModel->getRow($sql);
}

/**
 * 取得贺卡信息
 * @param   int     $card_id    贺卡id
 * @return  array   贺卡信息
 */
function card_info($card_id){
    $CommonModel	=	new CommonModel();
	$sql 			= 	"SELECT * FROM " . 'ybr_card' . " WHERE card_id = '$card_id'";
    return $CommonModel->getRow($sql);
}

/**
 * 获得订单需要支付的支付费用
 *
 * @access  public
 * @param   integer $payment_id
 * @param   float   $order_amount
 * @param   mix     $cod_fee
 * @return  float
 */
function pay_fee($payment_id, $order_amount, $cod_fee=null){
    $pay_fee 	= 	0;
    $payment 	= 	payment_info($payment_id);
    $rate    	= 	($payment['is_cod'] && !is_null($cod_fee)) ? $cod_fee : $payment['pay_fee'];

    if (strpos($rate, '%') !== false){
        /* 支付费用是一个比例 */
        $val     = floatval($rate) / 100;
        $pay_fee = $val > 0 ? $order_amount * $val /(1- $val) : 0;
    }
    else{
        $pay_fee = floatval($rate);
    }
    return round($pay_fee, 2);
}

/**
 * 将支付LOG插入数据表
 *
 * @access  public
 * @param   integer     $id         订单编号
 * @param   float       $amount     订单金额
 * @param   integer     $type       支付类型
 * @param   integer     $is_paid    是否已支付
 *
 * @return  int
 */
function insert_pay_log($id, $amount, $type = PAY_SURPLUS, $is_paid = 0){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'INSERT INTO ' . 'ybr_pay_log'." (order_id, order_amount, order_type, is_paid)" . " VALUES  ('$id', '$amount', '$type', '$is_paid')";
    $CommonModel->query($sql);
    return $CommonModel->insert_id();
}


/**
 * 计算积分的价值（能抵多少钱）
 * @param   int     $integral   积分
 * @return  float   积分价值
 */
function value_of_integral($integral){
    $scale = floatval($GLOBALS['_CFG']['integral_scale']);
    return $scale > 0 ? round(($integral / 100) * $scale, 2) : 0;
}

/**
 * 取得订单商品
 * @param   int     $order_id   订单id
 * @return  array   订单商品数组
 */
function order_goods($order_id){
    $sql 	= 	"SELECT rec_id, goods_id, goods_name, goods_sn, market_price, goods_number, " .
            	"goods_price, goods_attr, is_real, parent_id, is_gift, " .
            	"goods_price * goods_number AS subtotal, extension_code " .
            	"FROM " . 'ybr_order_goods' .
            	" WHERE order_id = '$order_id'";

    $res 	= 	M()->query($sql);
	foreach($res as $row){
		if ($row['extension_code'] == 'package_buy'){
            $row['package_goods_list'] 	= 	get_package_goods($row['goods_id']);
        }
        $goods_list[] 					= 	$row;
	}
    
    return $goods_list;
}


/**
 * 获得指定礼包的商品
 *
 * @access  public
 * @param   integer $package_id
 * @return  array
 */
function get_package_goods($package_id){
	
    $sql 	= 	"SELECT pg.goods_id, g.goods_name, pg.goods_number, p.goods_attr, p.product_number, p.product_id
            	FROM " . 'ybr_package_goods' . " AS pg
                LEFT JOIN " .'ybr_goods' . " AS g ON pg.goods_id = g.goods_id
                LEFT JOIN " . 'ybr_products' . " AS p ON pg.product_id = p.product_id
            	WHERE pg.package_id = '$package_id'";
    if ($package_id == 0){
        $sql .= " AND pg.admin_id = '$_SESSION[admin_id]'";
    }
    $resource = M()->query($sql);
    if (!$resource){
        return array();
    }

    $row 				= 	array();
    $good_product_str 	= 	'';
	/* 生成结果数组 取存在货品的商品id 组合商品id与货品id */
    foreach($resource as $_row){
    	if ($_row['product_id'] > 0){
            /* 取存商品id */
            $good_product_str .= ',' . $_row['goods_id'];
            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id'];
        }
        else{
            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'];
        }
        //生成结果数组
        $row[] = $_row;
    }
    
    $good_product_str 	= 	trim($good_product_str, ',');

    /* 释放空间 */
    unset($resource, $_row, $sql);

    /* 取商品属性 */
    if ($good_product_str != ''){
        $sql 				= 	"SELECT goods_attr_id, attr_value FROM " .'ybr_goods_attr'. " WHERE goods_id IN ($good_product_str)";
        $result_goods_attr 	= 	M()->query($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value){
            $_goods_attr[$value['goods_attr_id']] = $value['attr_value'];
        }
    }

    /* 过滤货品 */
    $format[0] 		= 	'%s[%s]--[%d]';
    $format[1] 		= 	'%s--[%d]';
    foreach ($row as $key => $value){
        if ($value['goods_attr'] != ''){
            $goods_attr_array 	= 	explode('|', $value['goods_attr']);

            $goods_attr 		= 	array();
            foreach ($goods_attr_array as $_attr){
                $goods_attr[] 	= 	$_goods_attr[$_attr];
            }
            $row[$key]['goods_name'] = sprintf($format[0], $value['goods_name'], implode('，', $goods_attr), $value['goods_number']);
        }
        else{
            $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['goods_number']);
        }
    }
    return $row;
}

/**
 * 查询购物车（订单id为0）或订单中是否有实体商品
 * @param   int     $order_id   订单id
 * @param   int     $flow_type  购物流程类型
 * @return  bool
 */
function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS){
	$CommonModel	=	new CommonModel();
    if ($order_id <= 0){
        $sql = "SELECT COUNT(*) FROM " . 'ybr_cart' .
                " WHERE session_id = '" . SESS_ID . "' AND is_real = 1 " .
                "AND rec_type = '$flow_type'";
    }
    else{
        $sql = "SELECT COUNT(*) FROM " . 'ybr_order_goods' .
                " WHERE order_id = '$order_id' AND is_real = 1";
    }
    // 测试
    //echo $sql;
    
    return $CommonModel->getOne($sql) > 0;
}

/**
 * 取得可用的支付方式列表
 * @param   bool    $support_cod        配送方式是否支持货到付款
 * @param   int     $cod_fee            货到付款手续费（当配送方式支持货到付款时才传此参数）
 * @param   int     $is_online          是否支持在线支付
 * @return  array   配送方式数组
 */
function available_payment_list($support_cod, $cod_fee = 0, $is_online = false){
    $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' .
            ' FROM ' . 'ybr_payment' .
            ' WHERE enabled = 1 ';
    if (!$support_cod){
        $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款
    }
    if ($is_online){
        $sql .= "AND is_online = '1' ";
    }
    $sql 		.= 	'ORDER BY pay_order'; // 排序
    $res 		= 	M()->query($sql);

    $pay_list 	= 	array();
    foreach($res as $row) {
    	 if ($row['is_cod'] == '1'){
            $row['pay_fee'] = $cod_fee;
        }
        $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] :
        price_format($row['pay_fee'], false);
        $modules[] = $row;
    }  
	    
    //include_once(ROOT_PATH.'includes/lib_compositor.php');
    import("@.Pay.Compositor");
    
    if(isset($modules)){
        return $modules;
    }
}


/**
 * 订单退款
 * @param   array   $order          订单
 * @param   int     $refund_type    退款方式 1 到帐户余额 2 到退款申请（先到余额，再申请提款） 3 不处理
 * @param   string  $refund_note    退款说明
 * @param   float   $refund_amount  退款金额（如果为0，取订单已付款金额）
 * @return  bool
 */
function order_refund($order, $refund_type, $refund_note, $refund_amount = 0){
	$CommonModel	=	new CommonModel();
    /* 检查参数 */
    $user_id 	= 	$order['user_id'];
    if ($user_id == 0 && $refund_type == 1){
        die('anonymous, cannot return to account balance');
    }

    $amount = $refund_amount > 0 ? $refund_amount : $order['money_paid'];
    if ($amount <= 0){
        return true;
    }

    if (!in_array($refund_type, array(1, 2, 3))){
        die('invalid params');
    }

    /* 备注信息 */
    if ($refund_note){
        $change_desc 	= 	$refund_note;
    }
    else{
        //include_once(ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/admin/order.php');
        $change_desc 	= 	sprintf(L('order_refund'), $order['order_sn']);
    }

    /* 处理退款 */
    if (1 == $refund_type){
        log_account_change($user_id, $amount, 0, 0, 0, $change_desc);
        return true;
    }
    elseif (2 == $refund_type){
        /* 如果非匿名，退回余额 */
        if ($user_id > 0){
            log_account_change($user_id, $amount, 0, 0, 0, $change_desc);
        }

        /* user_account 表增加提款申请记录 */
        $account = array(
            'user_id'      => $user_id,
            'amount'       => (-1) * $amount,
            'add_time'     => gmtime(),
            'user_note'    => $refund_note,
            'process_type' => SURPLUS_RETURN,
            'admin_user'   => $_SESSION['admin_name'],
            'admin_note'   => sprintf(L('order_refund'), $order['order_sn']),
            'is_paid'      => 0
        );
        $CommonModel->autoExecute('user_account', $account, 'INSERT');

        return true;
    }
    else{
        return true;
    }
}

/**
 * 取得用户地址列表
 * @param   int     $user_id    用户id
 * @return  array
 */
function address_list($user_id){
    $sql = "SELECT * FROM " . 'ybr_user_address' . " WHERE user_id = '$user_id'";
    return M()->query($sql);
}

/**
 * 取得可用的配送方式列表
 * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
 * @return  array   配送方式数组
 */
function available_shipping_list($region_id_list){
    $sql 	= 	'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
                's.shipping_desc, s.insure, s.support_cod, a.configure ' .
            	'FROM ' . 'ybr_shipping' . ' AS s, ' .
                'ybr_shipping_area' . ' AS a, ' .
                'ybr_area_region' . ' AS r ' .
            	'WHERE r.region_id ' . db_create_in($region_id_list) .
            	' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order';
	return M()->query($sql);
}

/**
 * 取得包装列表
 * @return  array   包装列表
 */
function pack_list(){
    $sql 	= 	'SELECT * FROM ' . 'ybr_pack';
    $res 	= 	M()->query($sql);

    $list = array();
    foreach($res as $row){
    	$row['format_pack_fee'] = price_format($row['pack_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }
    return $list;
}

/**
 * 取得贺卡列表
 * @return  array   贺卡列表
 */
function card_list(){
    $sql = "SELECT * FROM " . 'ybr_card';
    $res = M()->query($sql);

    $list = array();
    foreach($res as $row){
    	$row['format_card_fee'] = price_format($row['card_fee'], false);
        $row['format_free_money'] = price_format($row['free_money'], false);
        $list[] = $row;
    }
    return $list;
}


/**
 * 更新订单对应的 pay_log
 * 如果未支付，修改支付金额；否则，生成新的支付log
 * @param   int     $order_id   订单id
 */
function update_pay_log($order_id){
	$CommonModel	=	new CommonModel();
    $order_id 		= 	intval($order_id);
    if ($order_id > 0){
        $sql 			= 	"SELECT order_amount FROM " . 'ybr_order_info' .
                			" WHERE order_id = '$order_id'";
        $order_amount 	= 	$CommonModel->getOne($sql);
        if (!is_null($order_amount)){
            $sql 		= 	"SELECT log_id FROM " . 'ybr_pay_log' .
                    		" WHERE order_id = '$order_id'" .
                    		" AND order_type = '" . PAY_ORDER . "'" .
                    		" AND is_paid = 0";
            $log_id 	=	intval($CommonModel->getOne($sql));
            if ($log_id > 0){
                /* 未付款，更新支付金额 */
                $sql 	= 	"UPDATE " . 'ybr_pay_log' .
                        	" SET order_amount = '$order_amount' " .
                        	"WHERE log_id = '$log_id' LIMIT 1";
            }
            else{
                /* 已付款，生成新的pay_log */
                $sql 	= 	"INSERT INTO " . 'ybr_pay_log' .
                        	" (order_id, order_amount, order_type, is_paid)" .
                        	"VALUES('$order_id', '$order_amount', '" . PAY_ORDER . "', 0)";
            }
            $CommonModel->query($sql);
        }
    }
}


/**
 * 取指定规格的货品信息
 *
 * @access      public
 * @param       string      $goods_id
 * @param       array       $spec_goods_attr_id
 * @return      array
 */
function get_products_info($goods_id, $spec_goods_attr_id){
	$CommonModel			=	new CommonModel();
    $return_array 		= 	array();

    if (empty($spec_goods_attr_id) || !is_array($spec_goods_attr_id) || empty($goods_id)){
        return $return_array;
    }

    $goods_attr_array 	= 	sort_goods_attr_id_array($spec_goods_attr_id);

    if(isset($goods_attr_array['sort'])){
        $goods_attr 	= 	implode('|', $goods_attr_array['sort']);

        $sql 			= 	"SELECT * FROM " . 'ybr_products' . " WHERE goods_id = '$goods_id' AND goods_attr = '$goods_attr' LIMIT 0, 1";
        $return_array 	= 	$CommonModel->getRow($sql);
    }
    return $return_array;
}

/**
 * 将 goods_attr_id 的序列按照 attr_id 重新排序
 *
 * 注意：非规格属性的id会被排除
 *
 * @access      public
 * @param       array       $goods_attr_id_array        一维数组
 * @param       string      $sort                       序号：asc|desc，默认为：asc
 *
 * @return      string
 */
function sort_goods_attr_id_array($goods_attr_id_array, $sort = 'asc'){
    if (empty($goods_attr_id_array)){
        return $goods_attr_id_array;
    }

    //重新排序
    $sql 		= 	"SELECT a.attr_type, v.attr_value, v.goods_attr_id
            		FROM " .'ybr_attribute'. " AS a
            		LEFT JOIN " .'ybr_goods_attr'. " AS v
                	ON v.attr_id = a.attr_id
                	AND a.attr_type = 1
            		WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . "
            		ORDER BY a.attr_id $sort";
    $row 		= 	M()->query($sql);

    $return_arr = 	array();
    foreach ($row as $value){
        $return_arr['sort'][]   						= 	$value['goods_attr_id'];
        $return_arr['row'][$value['goods_attr_id']]    	=	 $value;
    }
    return $return_arr;
}

/**
 * 处理编辑订单时订单金额变动
 * @param   array   $order  订单信息
 * @param   array   $msgs   提示信息
 * @param   array   $links  链接信息
 */
function handle_order_money_change($order, &$msgs, &$links){
    $order_id 			= 	$order['order_id'];
    if ($order['pay_status'] == PS_PAYED || $order['pay_status'] == PS_PAYING){
        /* 应付款金额 */
        $money_dues 	= 	$order['order_amount'];
        if ($money_dues > 0){
            /* 修改订单为未付款 */
            update_order($order_id, array('pay_status' => PS_UNPAYED, 'pay_time' => 0));
            $msgs[]     = 	L('amount_increase');
            //$links[]    = 	array('text' => L('order_info') , 'href' => 'o?act=info&order_id=' . $order_id);
        }
        elseif ($money_dues < 0){
            $anonymous  = 	$order['user_id'] > 0 ? 0 : 1;
            $msgs[]     = 	L('amount_decrease');
            //$links[]    = 	array('text' => $GLOBALS['_LANG']['refund'], 'href' => 'order.php?act=process&func=load_refund&anonymous=' . $anonymous . '&order_id=' . $order_id . '&refund_amount=' . abs($money_dues));
        }
    }
}

/**
 * 查询配送区域属于哪个办事处管辖
 * @param   array   $regions    配送区域（1、2、3、4级按顺序）
 * @return  int     办事处id，可能为0
 */
function get_agency_by_regions($regions){
    if (!is_array($regions) || empty($regions)){
        return 0;
    }

    $arr 	= 	array();
    $sql 	= 	"SELECT region_id, agency_id " .
            	"FROM " . 'ybr_region' .
            	" WHERE region_id " . db_create_in($regions) .
            	" AND region_id > 0 AND agency_id > 0";
    $res 	= 	M()->query($sql);
    
    foreach($res as $row){
    	$arr[$row['region_id']] = $row['agency_id'];
    }

    if (empty($arr)){
        return 0;
    }

    $agency_id = 0;
    for ($i = count($regions) - 1; $i >= 0; $i--){
        if (isset($arr[$regions[$i]])){
            return $arr[$regions[$i]];
        }
    }
}

/**
 * 计算指定的金额需要多少积分
 *
 * @access  public
 * @param   integer $value  金额
 * @return  void
 */
function integral_of_value($value){
    $scale 	= 	floatval($GLOBALS['_CFG']['integral_scale']);
    return $scale > 0 ? round($value / $scale * 100) : 0;
}

/**
 * 取得配送方式信息
 * @param   int     $shipping_id    配送方式id
 * @return  array   配送方式信息
 */
function shipping_info($shipping_id){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'SELECT * FROM ' . 'ybr_shipping' .
            			" WHERE shipping_id = '$shipping_id' " .
            			'AND enabled = 1';
    return $CommonModel->getRow($sql);
}

/**
 * 取得用户地址信息
 * @param   int     $address_id     地址id
 * @return  array
 */
function address_info($address_id){
	$ComonModel		=	new CommonModel();
    $sql 			= 	"SELECT * FROM " . 'ybr_user_address' .
            			" WHERE address_id = '$address_id'";
	return $ComonModel->getRow($sql);
}

/**
 * 获得指定国家的所有省份
 *
 * @access      public
 * @param       int     country    国家的编号
 * @return      array
 */
function get_regions($type = 0, $parent = 0){
    $sql 	= 	'SELECT region_id, region_name FROM ' . 'ybr_region' .
            	" WHERE region_type = '$type' AND parent_id = '$parent'";
    return M()->query($sql);
}

/**
 * 取得红包信息
 * @param   int     $bonus_id   红包id
 * @param   string  $bonus_sn   红包序列号
 * @param   array   红包信息
 */
function bonus_info($bonus_id, $bonus_sn = ''){
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	"SELECT t.*, b.* " .
            			"FROM " . 'ybr_bonus_type' . " AS t," .
                		'ybr_user_bonus' . " AS b " .
            			"WHERE t.type_id = b.bonus_type_id ";
    if ($bonus_id > 0){
        $sql .= "AND b.bonus_id = '$bonus_id'";
    }
    else{
        $sql .= "AND b.bonus_sn = '$bonus_sn'";
    }
    return $CommonModel->getRow($sql);
}

/**
 * 取得用户当前可用红包
 * @param   int     $user_id        用户id
 * @param   float   $goods_amount   订单商品金额
 * @return  array   红包数组
 */
function user_bonus($user_id, $goods_amount = 0){
    $day    = 	getdate();
    $today  = 	local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

    $sql	= 	"SELECT t.type_id, t.type_name, t.type_money, b.bonus_id " .
            	"FROM " . 'ybr_bonus_type' . " AS t," .
                'ybr_user_bonus' . " AS b " .
            	"WHERE t.type_id = b.bonus_type_id " .
            	"AND t.use_start_date <= '$today' " .
            	"AND t.use_end_date >= '$today' " .
            	"AND t.min_goods_amount <= '$goods_amount' " .
            	"AND b.user_id<>0 " .
            	"AND b.user_id = '$user_id' " .
            	"AND b.order_id = 0";
    return M()->query($sql);
}


/**
 * 获得购物车中商品的总重量、总价格、总数量
 *
 * @access  public
 * @param   int     $type   类型：默认普通商品
 * @return  array
 */
function cart_weight_price($type = CART_GENERAL_GOODS){
	
	$CommonModel					=	new CommonModel();
	
    $package_row['weight'] 			= 	0;
    $package_row['amount'] 			= 	0;
    $package_row['number'] 			= 	0;

    $packages_row['free_shipping'] 	= 	1;

    /* 计算超值礼包内商品的相关配送参数 */
    $sql 							= 	'SELECT goods_id, goods_number, goods_price FROM ' . 'ybr_cart' . " WHERE extension_code = 'package_buy' AND session_id = '" . SESS_ID . "'";
    $row 							= 	M()->query($sql);

    if ($row){
        $packages_row['free_shipping'] 	= 	0;
        $free_shipping_count 			= 	0;

        foreach ($row as $val){
            // 如果商品全为免运费商品，设置一个标识变量
            $sql 						= 	'SELECT count(*) FROM ' .
						                    'ybr_package_goods' . ' AS pg, ' .
						                    'ybr_goods' . ' AS g ' .
						                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";
            $shipping_count 			= 	$CommonModel->getOne($sql);

            if ($shipping_count > 0){
                // 循环计算每个超值礼包商品的重量和数量，注意一个礼包中可能包换若干个同一商品
                $sql 					= 	'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' .
						                    'SUM(pg.goods_number) AS number FROM ' .
						                    'ybr_package_goods' . ' AS pg, ' .
						                    'ybr_goods' . ' AS g ' .
						                    "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '"  . $val['goods_id'] . "'";

                $goods_row 				= 	$CommonModel->getRow($sql);
                $package_row['weight'] 	+= 	floatval($goods_row['weight']) * $val['goods_number'];
                $package_row['amount']	+= 	floatval($val['goods_price']) * $val['goods_number'];
                $package_row['number'] 	+= 	intval($goods_row['number']) * $val['goods_number'];
            }
            else{
                $free_shipping_count++;
            }
        }

        $packages_row['free_shipping'] 	= 	$free_shipping_count == count($row) ? 1 : 0;
    }

    /* 获得购物车中非超值礼包商品的总重量 */
    $sql    							= 	'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' .
						                    'SUM(c.goods_price * c.goods_number) AS amount, ' .
						                    'SUM(c.goods_number) AS number '.
							                'FROM ' . 'ybr_cart' . ' AS c '.
							                'LEFT JOIN ' . 'ybr_goods' . ' AS g ON g.goods_id = c.goods_id '.
							                "WHERE c.session_id = '" . SESS_ID . "' " .
							                "AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy'";
    $row 								= 	$CommonModel->getRow($sql);

    $packages_row['weight'] 			= 	floatval($row['weight']) + $package_row['weight'];
    $packages_row['amount'] 			= 	floatval($row['amount']) + $package_row['amount'];
    $packages_row['number'] 			= 	intval($row['number']) + $package_row['number'];
    /* 格式化重量 */
    $packages_row['formated_weight'] 	= 	formated_weight($packages_row['weight']);

    return $packages_row;
}

/**
 * 获取推荐uid
 *
 * @access  public
 * @param   void
 *
 * @return int
 * @author xuanyan
 **/
function get_affiliate(){
	
	$CommonModel		=	new CommonModel();
	
    if (!empty($_COOKIE['ecshop_affiliate_uid'])){
        $uid 			= 	intval($_COOKIE['ecshop_affiliate_uid']);
        if ($CommonModel->getOne('SELECT user_id FROM ' . 'ybr_users' . "WHERE user_id = '$uid'")){
            return $uid;
        }
        else{
            setcookie('ecshop_affiliate_uid', '', 1);
        }
    }
    return 0;
}


/**
 * 设置红包为已使用
 * @param   int     $bonus_id   红包id
 * @param   int     $order_id   订单id
 * @return  bool
 */
function use_bonus($bonus_id, $order_id){
    $sql 		= 	"UPDATE " . 'ybr_user_bonus' .
		            " SET order_id = '$order_id', used_time = '" . gmtime() . "' " .
		            "WHERE bonus_id = '$bonus_id' LIMIT 1";

    return  M()->query($sql);
}

/**
 * 调用使用UCenter插件时的函数
 *
 * @param   string  $func
 * @param   array   $params
 *
 * @return  mixed
 */
function user_uc_call($func, $params = null){
//    if (isset($GLOBALS['_CFG']['integrate_code']) && $GLOBALS['_CFG']['integrate_code'] == 'ucenter'){
//        restore_error_handler();
//        if (!function_exists($func)){
//            include_once(ROOT_PATH . 'includes/lib_uc.php');
//        }
//
//        $res = call_user_func_array($func, $params);
//
//        set_error_handler('exception_handler');
//
//        return $res;
//    }
//    else{
//        return;
//    }
}














